Skip to main content

Advanced if

It is sometimes possible to drop the else. Consider the following example,

function checkInteger(integer) {
if (integer > 0) {
return "Positive";
} else {
return "Negative";
}
}

Since this function performs two distinct actions based on the outcome of the if and else condition, it can be rewritten by removing the else keyword,

function checkInteger(integer) {
if (integer > 0) {
return "Positive";
}
return "Negative";
}

These two functions will produce the same result. Because the return keyword terminates the function with the result. So, if the integer is greater than 0, the function returns Positive and the rest of the code is skipped. When the integer is less than 0, however, the code inside the if condition is not executed. As a result, the only line that runs is the last one, which is return Negative.